<template>
  <a-modal
    v-model:open="modalState"
    :title="modalTab === 1 ? '登陆' : '密码修改'"
    :keyboard="true"
    :footer="null"
    @cancel="
      () => {
        emits('close');
      }
    "
  >
    <div v-if="props.modalTab === 1" class="login">
      <a-form
        :model="formState"
        name="basic"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
        @finish="handleSubmit"
        @finishFailed="onFinishFailed"
      >
        <a-form-item label="账户：" name="username">
          <a-input v-model:value="formState.account" />
        </a-form-item>

        <a-form-item label="密码：" name="password">
          <a-input-password v-model:value="formState.password" />
        </a-form-item>
        <a-form-item :wrapper-col="{ offset: 8, span: 16 }" class="footer">
          <a-button type="primary" html-type="submit">提交</a-button>
        </a-form-item>
      </a-form>
    </div>
    <div v-else class="forgetPass">
      <a-form
        :model="formStateUpdatePassword"
        name="basic"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
        @finish="handleSubmit"
        @finishFailed="onFinishFailed"
        :rules="rulesUpdatePassword"
      >
        <a-form-item label="账户：" name="account">
          <a-input
            :disabled="true"
            v-model:value="formStateUpdatePassword.account"
          />
        </a-form-item>

        <a-form-item label="邮箱：" name="mailbox">
          <a-input
            :disabled="true"
            v-model:value="formStateUpdatePassword.mailbox"
          />
        </a-form-item>
        <a-form-item label="验证码：" name="verifyCode">
          <a-input v-model:value="formStateUpdatePassword.verifyCode" />
        </a-form-item>
        <a-form-item label="新密码：" name="newPassword">
          <a-input-password
            v-model:value="formStateUpdatePassword.newPassword"
          />
        </a-form-item>
        <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
          <a-button
            type="primary"
            @click="getVeriCode"
            style="margin-right: 10px"
            :disabled="verifyDisabled"
            >{{ verifyText }}</a-button
          >
          <a-button type="primary" html-type="submit">提交</a-button>
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import {
  getVerifiedCode,
  userLogin,
  updataPassword,
} from "@/api/methods/userReq";
import { computed, reactive, ref, watch } from "vue";
import { Message } from "@/utils/message";
import router from "@/router/router";
import { useLocalStorage } from "@vueuse/core";
import { IUpdatePassword } from "@/api/RequestIDL/userType";
import { userInfo, userInfoJson } from "@/utils/userInfo";
import { Rule } from "ant-design-vue/es/form/interface";

interface Props {
  modalShow: boolean;
  modalTab?: number;
}
const props = defineProps<Props>();
const emits = defineEmits(["close", "model"]);
interface FormState {
  account: string;
  password: string;
}
const modalState = computed(() => {
  return props.modalShow;
});
const formState = reactive<FormState>({
  account: "admin",
  password: "123",
});
const formStateUpdatePassword = ref<IUpdatePassword>({
  account: "",
  mailbox: "",
  newPassword: "",
  verifyCode: "",
});
const rulesUpdatePassword: Record<string, Rule[]> = {
  account: [{ required: true, message: "请填写账号！", trigger: "change" }],
  verifyCode: [
    {
      required: true,
      message: "请填写验证码",
      trigger: "change",
    },
  ],
  newPassword: [{ required: true, message: "请填写新密码", trigger: "change" }],
};
const onFinishFailed = (errorInfo: any) => {
  console.log("Failed:", errorInfo);
};
const handleSubmit = async () => {
  // 点击登录按钮 注册
  if (props.modalTab === 1) {
    const res = await userLogin(formState);
    if (res.code == 20000) {
      Message("success", "登陆成功", () => {
        const token = useLocalStorage<String>("token", "");
        userInfoJson.value = JSON.stringify(res.data);
        token.value = res.data.token;
        router.push({ path: "/home" });
      });
      emits("close", false);
      // window.location.reload();
    }
  } else {
    const res = await updataPassword(formStateUpdatePassword.value);
    if (res.code === 20000) {
      Message("success", "密码修改成功", () => {
        userInfoJson.value = "";
        router.push({ path: "/home" });
        emits("close", false);
      });
    }
  }
};
watch(
  userInfo,
  () => {
    formStateUpdatePassword.value.account = userInfo.value.account;
    formStateUpdatePassword.value.mailbox = userInfo.value.email;
  },
  { immediate: true }
);
const verifyDisabled = ref(false);
const verifyText = ref("点击获取验证码");
const getVeriCode = async () => {
  // TODO 获取验证码 message提示验证码
  verifyDisabled.value = true;
  const res = await getVerifiedCode(formStateUpdatePassword.value);
  if (res.code === 20000) {
    Message("success", "验证码已发送，请及时查看邮箱");
    let timer: any = null;
    let num = 30;
    if (!timer) {
      verifyDisabled.value = true;
      timer = setInterval(() => {
        if (num > 0) {
          num--;
          verifyText.value = `${num}秒后重新发送`;
        } else {
          verifyText.value = "点击获取验证码";
          verifyDisabled.value = false;
          clearInterval(timer);
          timer = null;
        }
      }, 1000);
    }
  } else {
    verifyDisabled.value = false;
    Message("error", "验证码获取失败，请联系管理员");
  }
};
</script>
<style scoped lang="scss"></style>
